package com.reggie.background.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.background.common.R;
import com.reggie.background.common.SMSUtils;
import com.reggie.background.common.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String requestURI = httpServletRequest.getRequestURI();
        String unFilter[]=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendSMS"
        };
        if (chackPath(unFilter,requestURI)) {
            log.info("请求放行资源：本次请求路径为{}",requestURI);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        if (httpServletRequest.getSession().getAttribute("employee")!=null) {
            log.info("已登录放行：本次请求路径为{}",requestURI);
            ThreadLocalUtils.setThreadLocalValue((Long) httpServletRequest.getSession().getAttribute("employee"));
            log.info("本次请求线程id为{}",Thread.currentThread().getId());
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if (httpServletRequest.getSession().getAttribute("user")!=null){
            log.info("已登录放行：本次请求路径为{}",requestURI);
            ThreadLocalUtils.setThreadLocalValue((Long) httpServletRequest.getSession().getAttribute("user"));
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        log.info("未登录请求未通过：本次请求路径为{}",requestURI);
        httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
    public boolean chackPath(String[] urls,String requestURI){
        for (String url : urls) {
            if (ANT_PATH_MATCHER.match(url,requestURI)) {
                return true;
            }
        }
        return false;

    }

}
